/*
 * Copyright (c) 2020 - present, Inspur Genersoft Co., Ltd.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *       http://www.apache.org/licenses/LICENSE-2.0
 *
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 */

package com.inspur.edp.lcm.metadata.core.thread;

import com.inspur.edp.lcm.metadata.api.entity.DbConnectionInfo;
import com.inspur.edp.lcm.metadata.api.service.ProjectExtendService;
import com.inspur.edp.lcm.metadata.inner.api.utils.IdeLogUtils;
import io.iec.edp.caf.boot.context.CAFContext;
import io.iec.edp.caf.core.session.CafSession;
import java.util.concurrent.CountDownLatch;
import java.util.function.Supplier;
import lombok.extern.slf4j.Slf4j;

/**
 * 部署任务
 */
@Slf4j
public class DeployTask implements Supplier<Boolean> {
    private String requestId;
    private DbConnectionInfo dbConnectionInfo;
    private ProjectExtendService projectExtendService;
    private String projPath;
    private CountDownLatch latch;
    private CafSession session;

    private DeployTask(String requestId, DbConnectionInfo dbConnectionInfo, CountDownLatch latch,
                       ProjectExtendService projectExtendService, String projPath, CafSession session) {
        this.requestId = requestId;
        this.dbConnectionInfo = dbConnectionInfo;
        this.latch = latch;
        this.projectExtendService = projectExtendService;
        this.projPath = projPath;
        this.session = session;
    }

    public static DeployTask ofDeployTask(String requestId, DbConnectionInfo dbConnectionInfo, CountDownLatch latch,
                                          ProjectExtendService projectExtendService, String projPath, CafSession session) {
        return new DeployTask(requestId, dbConnectionInfo, latch, projectExtendService, projPath, session);
    }

    @Override
    public Boolean get() {
        try {
            CAFContext.current.getService().setCurrentThreadPoolSession(session);
            IdeLogUtils.setRequestId(requestId);
            projectExtendService.deploy(dbConnectionInfo, "", projPath, "1");
            return true;
        } finally {
            latch.countDown();
            CAFContext.current.getService().clearCurrentThreadPoolSession();
        }
    }
}
